package mango.service;

import java.util.concurrent.ConcurrentHashMap;

public final class ServiceManager {
	private static final ConcurrentHashMap<String, Object> SERVICE_POOL = new ConcurrentHashMap<String, Object>();

	@SuppressWarnings("unchecked")
	public static final <E> E getService(Class<E> clazz) {
		Object service = SERVICE_POOL.get(clazz.getCanonicalName());
		if (service != null) {
			return (E) service;
		}
		Service serviceAnno = clazz.getAnnotation(Service.class);
		try {
			if (serviceAnno == null) {
				return clazz.newInstance();
			}
			else {
				service = clazz.newInstance();
				SERVICE_POOL.put(clazz.getCanonicalName(), service);
				return (E) service;
			}
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
